<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { characterApi, photoApi, type Character } from '../../services/api'

const router = useRouter()
const step = ref(1)
const totalSteps = ref(3)
const isLoading = ref(false)
const error = ref<string | null>(null)
const previewUrl = ref<string | null>(null)

// 表单数据
const characterData = ref({
  name: '',
  description: '',
  photo: null as File | null
})

const character = ref<Character | null>(null)

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (file) {
    characterData.value.photo = file
    // 创建预览URL
    previewUrl.value = URL.createObjectURL(file)
  }
}

// 更新当前步骤
const nextStep = () => {
  if (step.value < totalSteps.value) {
    step.value++
  }
}

const prevStep = () => {
  if (step.value > 1) {
    step.value--
  }
}


// 提交角色创建
const submitCharacter = async () => {
  if (!characterData.value.name.trim()) {
    window.showNotification('请输入角色名称', 'error')
    return
  }
  
  if (!characterData.value.photo) {
    window.showNotification('请选择照片', 'error')
    return
  }
  
  try {
    isLoading.value = true
    error.value = null
    
    // 首先上传照片
    const formData = new FormData()
    formData.append('photo', characterData.value.photo)
    
    const photoResponse: any = await photoApi.upload(formData)
    
    // 然后创建角色
    const newCharacter = await characterApi.create({
      name: characterData.value.name,
      personality: characterData.value.description,
      emoji_data: `http://localhost:3001/${photoResponse.file_path}`
    })
    
    character.value = newCharacter
    
    window.showNotification('角色创建成功！', 'success')
    
    // 前往下一步
    nextStep()
  } catch (err) {
    console.error('创建角色失败:', err)
    let errorMessage = '创建角色失败'
    
    if (err instanceof Error) {
      // 网络错误
      if (err.message.includes('Failed to fetch') || err.message.includes('fetch')) {
        errorMessage = '无法连接到服务器，请确保后端服务正在运行'
      } else {
        errorMessage = err.message
      }
    } else if (typeof err === 'string') {
      errorMessage = err
    }
    
    error.value = errorMessage
    window.showNotification(errorMessage, 'error')
  } finally {
    isLoading.value = false
  }
}

// 前往聊天页面
const goToChat = () => {
  if (character.value?.id) {
    router.push(`/chat?characterId=${character.value.id}`)
  }
}
</script>

<template>
  <div class="character-create-container">
    <h1 class="page-title">创建角色</h1>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message neo-brutalist">
      {{ error }}
    </div>
    
    <div class="creation-content">
      <!-- 步骤1: 基本信息 -->
      <div v-if="step === 1" class="creation-step neo-brutalist">
        <h2>步骤 1: 角色基本信息</h2>
        <form @submit.prevent="nextStep">
          <div class="form-group">
            <label for="name">角色名称 *</label>
            <input
              id="name"
              v-model="characterData.name"
              type="text"
              placeholder="输入角色名称"
              :disabled="isLoading"
              class="neo-brutalist-input"
              maxlength="50"
            />
            <div class="char-count">{{ characterData.name.length }}/50</div>
          </div>
          
          <div class="form-group">
            <label for="description">角色描述</label>
            <textarea
              id="description"
              v-model="characterData.description"
              placeholder="描述你的角色（可选）"
              :disabled="isLoading"
              class="neo-brutalist-input"
              rows="4"
              maxlength="200"
            ></textarea>
            <div class="char-count">{{ characterData.description.length }}/200</div>
          </div>
          
          <div class="form-actions">
            <button
              type="submit"
              class="next-button neo-brutalist btn btn--primary"
              :disabled="!characterData.name.trim() || isLoading"
            >
              下一步
            </button>
          </div>
        </form>
      </div>
      
      <!-- 步骤2: 上传照片 -->
      <div v-else-if="step === 2" class="creation-step neo-brutalist">
        <h2>步骤 2: 上传照片</h2>
        <form @submit.prevent="submitCharacter">
          <div class="form-group">
            <label for="photo">选择照片 *</label>
            <div class="photo-upload">
              <div class="file-upload-area" v-if="!previewUrl">
                <input
                  type="file"
                  id="photo"
                  accept="image/*"
                  @change="handleFileSelect"
                  style="display: none;"
                />
                <label for="photo" class="upload-button neo-brutalist btn btn--primary">
                  选择照片
                </label>
                <p class="upload-instruction">请选择一张清晰的正面照片</p>
              </div>
              
              <div class="preview-area" v-else>
                <img :src="previewUrl" alt="预览照片" class="preview-image" />
                <div class="preview-actions">
                  <button @click="previewUrl = null" class="reset-button neo-brutalist btn btn--danger">
                    重新选择
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="form-actions">
            <button
              type="button"
              class="prev-button neo-brutalist btn btn--secondary"
              @click="prevStep"
              :disabled="isLoading"
            >
              上一步
            </button>
            <button
              type="submit"
              class="submit-button neo-brutalist btn btn--primary"
              :disabled="!characterData.photo || isLoading"
              :class="{ 'btn--disabled': isLoading }"
            >
              {{ isLoading ? '创建中...' : '创建角色' }}
            </button>
          </div>
        </form>
      </div>
      
      <!-- 步骤3: 完成 -->
      <div v-else-if="step === 3" class="creation-step neo-brutalist">
        <h2>🎉 角色创建完成!</h2>
        <div class="completion-content">
          <div class="character-preview" v-if="character">
            <img :src="character.emoji_data" :alt="character.name" class="character-image" />
            <h3>{{ character.name }}</h3>
            <p>{{ character.personality || '暂无描述' }}</p>
          </div>
          
          <div class="completion-actions">
            <button
              class="chat-button neo-brutalist btn btn--primary"
              @click="goToChat"
            >
              与角色聊天
            </button>
            <button
              class="home-button neo-brutalist btn btn--secondary"
              @click="router.push('/home')"
            >
              返回主页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.character-create-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.character-create-container .page-title {
  text-align: center;
  margin-bottom: 2rem;
  color: #000;
  font-family: 'Bebas Neue', sans-serif;
  letter-spacing: 2px;
  font-size: 2.5rem;
}

.error-message {
  background-color: #ffe0e0;
  border-color: #ff4444;
  color: #ff4444;
  padding: 1rem;
  margin-bottom: 2rem;
  border-left: 8px solid #ff4444;
}

.form-group {
  margin-bottom: 2rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.75rem;
  font-weight: bold;
  font-family: 'Bebas Neue', sans-serif;
  letter-spacing: 1px;
  color: #000;
}

.neo-brutalist-input {
  width: 100%;
  padding: 1rem;
  font-size: 1rem;
  font-family: 'Roboto Mono', monospace;
  border: 4px solid #000;
  box-shadow: 4px 4px 0 #000;
  transition: all 0.2s ease;
  border-radius: 4px;
  font-weight: 500;
  resize: vertical;
  min-height: 48px;
  box-sizing: border-box;
  background-color: #fff;
  color: #000;
}

.neo-brutalist-input:focus {
  outline: none;
  box-shadow: 2px 2px 0 #000;
  transform: translate(2px, 2px);
}

.char-count {
  margin-top: 0.5rem;
  text-align: right;
  font-size: 0.875rem;
  color: #666;
  font-family: 'Roboto Mono', monospace;
}

.photo-upload {
  border: 4px dashed #000;
  padding: 2rem;
  text-align: center;
  border-radius: 4px;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  margin-bottom: 1rem;
  border: 4px solid #000;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 2rem;
  gap: 1rem;
}

.completion-content {
  text-align: center;
  padding: 2rem 0;
}

.character-image {
  max-width: 200px;
  max-height: 200px;
  margin-bottom: 2rem;
  border: 4px solid #000;
  border-radius: 4px;
}

.completion-actions {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 3rem;
  align-items: center;
}

/* Neo Brutalist Styles 已在脚本部分定义，保持原有样式不变 */
@media (max-width: 768px) {
  .creation-steps {
    grid-template-columns: 1fr;
  }
  
  .character-create-container {
    padding: 1rem;
  }
  
  .character-create-container .page-title {
    font-size: 2rem;
  }
}
</style>